package com.gframework.mybatis.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gframework.mybatis.dao.ITableBasicDAO;
import com.gframework.mybatis.service.IService;
import com.gframework.mybatis.service.ITableService;
import com.gframework.mybatis.service.IViewService;
import com.gframework.sqlparam.BeanSqlParam;
import com.gframework.sqlparam.SqlParam;

/**
 * ITableService 公共接口基本实现类
 * 
 * @since 2.0.0
 * @author Ghwolf
 * @see ITableService
 * @see IViewService
 * @see IService
 * @see ViewServiceImpl
 * @see ServiceImpl
 */
public class TableServiceImpl<M extends ITableBasicDAO<T>, T extends Serializable> extends ViewServiceImpl<M, T>
		implements ITableService<M, T> {

	@Override
	@Transactional(isolation = Isolation.READ_UNCOMMITTED)
	public Serializable save(T pojo) {
		Assert.notNull(pojo, "pojo不能为null！");
		return getDao().save(pojo);
	}

	@Override
	@Transactional(isolation = Isolation.READ_UNCOMMITTED)
	public int saveBatch(Collection<T> pojos) {
		Assert.notNull(pojos, "pojos不能为null！");
		return getDao().saveBatch(pojos);
	}

	@Override
	@Transactional(isolation = Isolation.READ_UNCOMMITTED)
	public int saveBatch(Collection<T> pojos, int maximum) {
		Assert.notNull(pojos, "pojos不能为null！");
		Assert.isTrue(maximum >= 1, "maximum必须>=1！");
		List<T> list = new ArrayList<>(maximum);
		int n = 0;
		for (T t : pojos) {
			list.add(t);
			if (list.size() == maximum) {
				n += this.saveBatch(pojos);
				list.clear();
			}
		}
		if (!list.isEmpty()) {
			n += this.saveBatch(list);
		}
		return n;
	}

	@Override
	@Transactional
	public int update(BeanSqlParam<T> beanSqlParam) {
		if (beanSqlParam == null || beanSqlParam.getPojo() == null) return 0;
		return getDao().update(beanSqlParam);
	}

	@Override
	@Transactional
	public int delete(SqlParam sqlParam) {
		if (sqlParam == null) return 0;
		return getDao().delete(sqlParam);
	}

}
